package Model;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class LoginModel {
	public static LoginModel shareModel = new LoginModel();
	int userID;	String creditID;
	
	final static String loginAddr = "http://happywaiman.dlinkddns.com/Reserve/User/login.php?action=login&acName=_ac&pw=_pw";
	public Boolean login(String username, String password) {
		String addr = loginAddr.replaceAll("_ac", username);
		addr = addr.replaceAll("_pw", password);
		try {
			URL url = new URL(addr);
			ReadFromURL rfu = new ReadFromURL();
			String content = rfu.getContentFromURL(url);
			JSONObject obj;
			obj = new JSONObject(content);
			Iterator<String> it = obj.keys();
			Boolean state = false;
			while (it.hasNext()) {
				String key = it.next();
				if ("state".equalsIgnoreCase(key)) {
					state = obj.getBoolean(key);
				} else if ("id".equalsIgnoreCase(key)) {
					userID = obj.getInt(key);
				} else if ("uuid".equalsIgnoreCase(key)) {
					creditID = obj.getString(key);
				}
			}
			return state;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String query(String address) {
		String newAddr = address.replaceAll("_uid", Integer.toString(userID));
		newAddr = newAddr.replaceAll("_cid", creditID);
		URL u;
		try {
			u = new URL(newAddr);
			ReadFromURL reader = new ReadFromURL();
			String s = reader.getContentFromURL(u);
			JSONObject obj = new JSONObject(s);
			Iterator<String> it = obj.keys();
			Boolean state = false;	String newCredit = null;	String content = null;
			while (it.hasNext()) {
				String key = it.next();
				if ("state".equalsIgnoreCase(key)) {
					state = obj.getBoolean(key);
				} else if ("pass".equalsIgnoreCase(key)) {
					newCredit = obj.getString(key);
				} else if ("content".equalsIgnoreCase(key)) {
					content = obj.getString(key);
				}
			}
			if (state)
				return content;
			else {
				creditID = null;
				return query(address);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
